package cn.zust.itcost.service.impl;

import cn.zust.itcost.entity.graph.node.*;
import cn.zust.itcost.repository.ResumeRepository;
import cn.zust.itcost.service.ResumeAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ResumeAnalysisServiceImpl implements ResumeAnalysisService {

    @Autowired
    private ResumeRepository resumeRepository;

    @Override
    public Map<String, Object> analyzeResume(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        List<String> suggestions = new ArrayList<>();
        
        // 1. 分析教育经历
        analyzeEducation(resume.getEducations(), suggestions);
        
        // 2. 分析工作经历
        analyzeExperience(resume.getExperiences(), suggestions);
        
        // 3. 分析技能
        analyzeSkills(resume.getSkills(), suggestions);
        
        // 4. 分析整体内容
        analyzeContent(resume.getContent(), suggestions);
        
        return Map.of(
            "resumeId", resumeId,
            "suggestions", suggestions,
            "score", calculateScore(resume)
        );
    }

    @Override
    public Map<String, Object> scoreResume(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        return Map.of(
            "resumeId", resumeId,
            "score", calculateScore(resume),
            "scoreDetails", calculateScoreDetails(resume)
        );
    }

    @Override
    public Map<String, Object> analyzeKeywords(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        return Map.of(
            "resumeId", resumeId,
            "keywords", extractKeywords(resume),
            "keywordFrequency", calculateKeywordFrequency(resume)
        );
    }

    private void analyzeEducation(List<EducationNode> educations, List<String> suggestions) {
        if (educations == null || educations.isEmpty()) {
            suggestions.add("建议添加教育经历信息");
            return;
        }
        
        for (EducationNode education : educations) {
            if (education.getSchool() == null || education.getSchool().isEmpty()) {
                suggestions.add("教育经历中缺少学校名称");
            }
            if (education.getMajor() == null || education.getMajor().isEmpty()) {
                suggestions.add("教育经历中缺少专业信息");
            }
            if (education.getDegree() == null || education.getDegree().isEmpty()) {
                suggestions.add("教育经历中缺少学位信息");
            }
            if (education.getStartDate() == null || education.getEndDate() == null) {
                suggestions.add("教育经历中缺少时间信息");
            }
        }
    }

    private void analyzeExperience(List<ExperienceNode> experiences, List<String> suggestions) {
        if (experiences == null || experiences.isEmpty()) {
            suggestions.add("建议添加工作经历信息");
            return;
        }
        
        for (ExperienceNode experience : experiences) {
            if (experience.getCompany() == null || experience.getCompany().isEmpty()) {
                suggestions.add("工作经历中缺少公司名称");
            }
            if (experience.getPosition() == null || experience.getPosition().isEmpty()) {
                suggestions.add("工作经历中缺少职位信息");
            }
            if (experience.getStartDate() == null || experience.getEndDate() == null) {
                suggestions.add("工作经历中缺少时间信息");
            }
            if (experience.getDescription() == null || experience.getDescription().isEmpty()) {
                suggestions.add("工作经历中缺少工作内容描述");
            }
            if (experience.getAchievements() == null || experience.getAchievements().isEmpty()) {
                suggestions.add("建议添加工作成果和业绩");
            }
        }
    }

    private void analyzeSkills(List<SkillNode> skills, List<String> suggestions) {
        if (skills == null || skills.isEmpty()) {
            suggestions.add("建议添加技能信息");
            return;
        }
        
        if (skills.size() < 5) {
            suggestions.add("技能数量较少，建议添加更多相关技能");
        }
        
        // 检查技能描述的详细程度
        for (SkillNode skill : skills) {
            if (skill.getName() == null || skill.getName().isEmpty()) {
                suggestions.add("技能描述不完整");
            }
        }
    }

    private void analyzeContent(String content, List<String> suggestions) {
        if (content == null || content.isEmpty()) {
            suggestions.add("简历内容为空");
            return;
        }
        
        // 检查内容长度
        if (content.length() < 500) {
            suggestions.add("简历内容过于简短，建议补充更多详细信息");
        }
        
        // 检查关键词密度
        if (!content.contains("项目") && !content.contains("经验")) {
            suggestions.add("建议添加项目经验描述");
        }
        
        if (!content.contains("技能") && !content.contains("能力")) {
            suggestions.add("建议添加技能和能力描述");
        }
    }

    private int calculateScore(ResumeNode resume) {
        int score = 0;
        
        // 教育经历评分
        if (resume.getEducations() != null && !resume.getEducations().isEmpty()) {
            score += 20;
        }
        
        // 工作经历评分
        if (resume.getExperiences() != null && !resume.getExperiences().isEmpty()) {
            score += 30;
        }
        
        // 技能评分
        if (resume.getSkills() != null && !resume.getSkills().isEmpty()) {
            score += 20;
        }
        
        // 内容完整性评分
        if (resume.getContent() != null && !resume.getContent().isEmpty()) {
            score += 30;
        }
        
        return score;
    }

    private Map<String, Integer> calculateScoreDetails(ResumeNode resume) {
        Map<String, Integer> details = new HashMap<>();
        
        // 教育经历评分
        details.put("educationScore", resume.getEducations() != null && !resume.getEducations().isEmpty() ? 20 : 0);
        
        // 工作经历评分
        details.put("experienceScore", resume.getExperiences() != null && !resume.getExperiences().isEmpty() ? 30 : 0);
        
        // 技能评分
        details.put("skillScore", resume.getSkills() != null && !resume.getSkills().isEmpty() ? 20 : 0);
        
        // 内容完整性评分
        details.put("contentScore", resume.getContent() != null && !resume.getContent().isEmpty() ? 30 : 0);
        
        return details;
    }

    private List<String> extractKeywords(ResumeNode resume) {
        Set<String> keywords = new HashSet<>();
        
        // 从教育经历中提取关键词
        if (resume.getEducations() != null) {
            resume.getEducations().forEach(education -> {
                if (education.getSchool() != null) keywords.add(education.getSchool());
                if (education.getMajor() != null) keywords.add(education.getMajor());
                if (education.getDegree() != null) keywords.add(education.getDegree());
            });
        }
        
        // 从工作经历中提取关键词
        if (resume.getExperiences() != null) {
            resume.getExperiences().forEach(experience -> {
                if (experience.getCompany() != null) keywords.add(experience.getCompany());
                if (experience.getPosition() != null) keywords.add(experience.getPosition());
            });
        }
        
        // 从技能中提取关键词
        if (resume.getSkills() != null) {
            resume.getSkills().forEach(skill -> {
                if (skill.getName() != null) keywords.add(skill.getName());
            });
        }
        
        return new ArrayList<>(keywords);
    }

    private Map<String, Integer> calculateKeywordFrequency(ResumeNode resume) {
        Map<String, Integer> frequency = new HashMap<>();
        
        if (resume.getContent() != null) {
            String content = resume.getContent().toLowerCase();
            
            // 统计常见关键词出现频率
            String[] commonKeywords = {"项目", "经验", "技能", "开发", "设计", "管理", "分析", "优化", "实现", "负责"};
            for (String keyword : commonKeywords) {
                int count = (content.length() - content.replace(keyword, "").length()) / keyword.length();
                if (count > 0) {
                    frequency.put(keyword, count);
                }
            }
        }
        
        return frequency;
    }
} 